﻿using System.Data.Common;
using feather.core;
using Newtonsoft.Json;

namespace feather.finder
{
    /// <summary>
    /// 使用SQL查询，得到Action对象
    /// </summary>
    public class SQLActionFinder : ActionFinder
    {
        /// <summary>
        /// 寻找方法
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public object Find(string uri)
        {
            string action = null;
            using (DbCommand dbCommand = DbConnection.CreateCommand())
            {
                dbCommand.CommandText = string.Format(SQL, uri);

                using (DbDataReader dbDataReader = dbCommand.ExecuteReader())
                {
                    if (dbDataReader.HasRows && dbDataReader.Read())
                    {
                        action = dbDataReader.GetString(0);
                        object newAction = JsonConvert.DeserializeObject(action);
                        if (newAction != null)
                            return newAction;
                    }
                    
                }
            }
            return action;
        }

        /// <summary>
        /// 查询SQL
        /// </summary>
        public string SQL { get; set; }

        /// <summary>
        /// 数据连接对象
        /// </summary>
        public DbConnection DbConnection { get; set; }
    }
}
